import sys
import os
import string
import secrets
import jwt
import datetime

from pydub import AudioSegment
import io


from flask import  send_file
import json





from pathlib import Path
# 动态添加utils文件夹的路径
current_file_path = Path(os.path.abspath(__file__))
parent_dir = current_file_path.parent.parent
print(parent_dir)
sys.path.append(os.path.join(parent_dir, 'models'))
from  models  import  assistantLoginModel
sys.path.append(os.path.join(parent_dir, 'utils'))
from utils import  util
from utils import  qwen_util








def recordingMinutes_convert_to_aac_save_test(audio_file,total_duration,actual_duration,pause_count):
    """登录页面。
         Args:
          :功能: 保存页面录制的音频
          :audio_file : 音频文件
         ：total_duration：  总体时间
         ：actual_duration ： 有效时间
         ：pause_count  ： 暂停次数
         :return: 成功返回 1    失败返回  0    失败原因

         Returns:
             result: 成功： success   失败: false

    """

    try:
        # 读取上传的音频文件
        audio_data = audio_file.read()
        print(f"收到音频数据大小: {len(audio_data)} 字节")

        # 转换为AudioSegment（从webm格式）
        audio = AudioSegment.from_file(io.BytesIO(audio_data), format="webm")

        # 获取音频信息
        duration_sec = len(audio) / 1000  # 转换为秒
        sample_rate = audio.frame_rate
        channels = audio.channels

        print(f"音频信息: 时长={duration_sec:.2f}s, 采样率={sample_rate}Hz, 声道数={channels}")

        # 生成文件名（基于时间戳）
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        base_filename = f"recording_{timestamp}"

        # 创建保存目录
        recordings_dir = "recordings"
        os.makedirs(recordings_dir, exist_ok=True)

        # 1. 保存为WAV文件到服务器
        wav_filename = f"{base_filename}.wav"
        tmp_wav_filepath = os.path.join(recordings_dir, "tmp_" + wav_filename)

        audio.export(tmp_wav_filepath, format="wav")
        # audio.set_frame_rate(16000).export(wav_filepath, format="wav")
        wav_filesize = os.path.getsize(tmp_wav_filepath)
        # print(f"WAV文件已保存: {tmp_wav_filepath} ({wav_filesize} 字节)")
        #
        # audio_final = AudioSegment.from_file(tmp_wav_filepath)
        # # 音频处理：转换为16kHz，单声道
        # target_sample_rate = 16000
        # processed_audio = audio_final.set_frame_rate(target_sample_rate).set_channels(1)
        #
        # # 获取处理后的信息
        # processed_duration_sec = len(processed_audio) / 1000
        # print(f"处理后音频: 时长={processed_duration_sec:.2f}s, 采样率={target_sample_rate}Hz, 声道数=1")
        #
        # wav_filepath = os.path.join(recordings_dir, wav_filename)
        # audio_final.export(wav_filepath, format="wav")

        wav_filepath = os.path.join(recordings_dir, wav_filename)
        save_success = util.convert_to_16k_librosa(tmp_wav_filepath, wav_filepath)
        if save_success :
            util.delete_file_os(tmp_wav_filepath)

        fileLink = util.ossUploader(wav_filepath)

        accessKeyId = 'LTAI5tMQb14jQttyw9C78XnN'  # os.getenv('ALIYUN_AK_ID')
        accessKeySecret = '3Xt54SPo2h82VmFE0k1PYYLBrfqhzR'  # os.getenv('ALIYUN_AK_SECRET')
        appKey = 'RgY65M8PEqOJqaGs'  # os.getenv('NLS_APP_KEY')

        # fileLink = "https://voiceprint-recognition.oss-cn-hangzhou.aliyuncs.com/waveList/recording_20251022_104309.wav"
        current_path = os.getcwd()
        wav_filepath = current_path +"/"+ wav_filepath

        filename = os.path.basename(wav_filepath)[:-4] + ".txt"
        directory = os.path.dirname(wav_filepath)
        print("  filename =  ")
        print(filename)
        print("  directory = ")
        print(directory)

        txtFile = directory + "/" + filename
        if  fileLink != None :
            sentencesList = util.fileTrans(accessKeyId, accessKeySecret, appKey, fileLink)
            if  sentencesList != None  and   len(sentencesList) > 0 :
                content = ''
                for sentence in sentencesList:
                    print(sentence)
                    content = content + "  SpeakerId :  " + sentence['SpeakerId'] + "   Text  :    " +sentence['Text']
                    # 追加模式写入结果
                    with open(txtFile, 'a', encoding='utf-8') as file:
                         file.write(sentence['Text'] + "\n")

                inputMessage = "请提取下面一段话的主题,如果有事务安排，请根据关键词如 需要、请、安排、麻烦、 负责 +责任人+时间 提取出任务清单，包括：姓名，任务内容、任务开始时间和任务结束时间： " + content
                qwen_util.qwen_plus_(inputMessage)



        # 2. 在内存中转换为AAC用于下载
        aac_buffer = io.BytesIO()
        audio.export(aac_buffer, format="adts", codec="aac", bitrate="128k")
        aac_buffer.seek(0)

        # 3. 同时保存AAC文件到服务器
        aac_filename = f"{base_filename}.aac"
        aac_filepath = os.path.join(recordings_dir, aac_filename)
        audio.export(aac_filepath, format="adts", codec="aac", bitrate="128k")
        aac_filesize = os.path.getsize(aac_filepath)
        print(f"AAC文件已保存: {aac_filepath} ({aac_filesize} 字节)")

        # 保存录制信息到文本文件
        info_filename = f"{base_filename}_info.txt"
        info_filepath = os.path.join(recordings_dir, info_filename)
        with open(info_filepath, 'w', encoding='utf-8') as f:
            f.write(f"录制信息文件\n")
            f.write(f"============\n")
            f.write(f"文件名: {base_filename}\n")
            f.write(f"录制时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"总时长: {total_duration} 秒\n")
            f.write(f"有效录制: {actual_duration} 秒\n")
            f.write(f"暂停次数: {pause_count}\n")
            f.write(f"音频时长: {duration_sec:.2f} 秒\n")
            f.write(f"采样率: {sample_rate} Hz\n")
            f.write(f"声道数: {channels}\n")
            f.write(f"WAV文件: {wav_filename} ({wav_filesize} 字节)\n")
            f.write(f"AAC文件: {aac_filename} ({aac_filesize} 字节)\n")

        print(f"录制信息已保存: {info_filepath}")


        #  本地语音识别
        # inputWav = '/media/qy/sdb1/projects/test1/2speakers_example.wav'
        # current_path = os.getcwd()
        # wav_filepath = current_path +"/"+ wav_filepath
        # # realTimeSpeechRecognition.multiruntest(wav_filepath,1)
        # # recogResult = realTimeSpeechRecognition.singleruntest(wav_filepath)
        # recogResult = realTimeSpeechRecognition_join.singleruntest_simple(wav_filepath)
        # if  recogResult == 1:
        #     filename = os.path.basename(wav_filepath)[:-4] + ".txt"
        #     directory = os.path.dirname(wav_filepath)
        #     print("  filename =  ")
        #     print(filename)
        #     print("  directory = ")
        #     print(directory)
        #
        #     txtFile= directory + "/"  + filename
        #     # content = read_txt_file(txtFile)
        #     # if content:
        #     #     print("文件内容:")
        #     #     print(content)
        #
        #     # 逐行读取
        #     lines = util.read_txt_lines(txtFile)
        #     content =''
        #     if lines:
        #         print("\n文件行数:", len(lines))
        #         for i, line in enumerate(lines, 1):
        #             print(f"第{i}行: {line}")
        #             content =  content + line
        #
        #     inputMessage = "请提取下面一段话的主题： " + content
        #     qwen_util.qwen_plus_(inputMessage)





        # # 返回AAC文件给用户下载
        # return send_file(
        #     aac_buffer,
        #     as_attachment=True,
        #     download_name=f'{base_filename}.aac',
        #     mimetype='audio/aac'
        # )

    except Exception as e:
        print(f"转换失败: {str(e)}")
        return f'转换失败: {str(e)}', 500



    result =  0
    reason = "请检查机构、账号和密码是否正确"
    data = {
        "result": result,
        "reason": reason,
        "tokenId": None
    }


    return data















